package cn.edu.nju.software.jungle;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * 
 * @author Jungle Yang
 * Generate the hmac 
 */
public class HmacGenerator {
	public static String MD5_HASHING = "MD5";
	public static String SHA1_HASHING = "SHA-1";
	public static String SHA256_HASHING = "SHA-256";
	
	/**
	 * @param origin The string we want to encrypt.
	 * @param type The encrypt type, can be md5, sha-1, sha-256.
	 * @return The hmac.
	 */
	public static String hash(String origin, String type){
		MessageDigest algorithm = null;
		String hash = null;
		type = (type==null?null:type.toUpperCase());
		try{
			if(MD5_HASHING.equals(type)){
				algorithm = MessageDigest.getInstance(MD5_HASHING);
			}else if(SHA1_HASHING.equals(type)){
				algorithm = MessageDigest.getInstance(SHA1_HASHING);
			}else if(SHA256_HASHING.equals(type)){
				algorithm = MessageDigest.getInstance(SHA256_HASHING);
			}else{
				//default md5
				algorithm = MessageDigest.getInstance(MD5_HASHING);
			}
		}catch(NoSuchAlgorithmException nsae){
			throw new RuntimeException(nsae);
		}
		algorithm.reset();
		algorithm.update(origin.getBytes());
		hash = bytesToHex(algorithm.digest());
		//use lower case
		return hash.toLowerCase();
	}
	
	/**
	 * @param bytes The source bytes.
	 * @return The Hex string.
	 */
	public static String bytesToHex(byte[] bytes){
		 StringBuilder hex = new StringBuilder(); 
		 for (int i=0; i<bytes.length; i++) {
				String tmp = Integer.toHexString(0xFF & bytes[i]);
				if(hex.length()==1){
					hex.append('0');
				}
				hex.append(tmp);
			}
		 return hex.toString();		
	}
}
